package com.company.zonghelizi.jihe.myjihe;
/**
 * 双向链表实现
 * 双项链表
 * 只做了添加到首位
 */
public class MyLinkedListDouble {
    private Node2 fistNode = null;
    private Node2 lastNode = null;
    private int size = 0;

    public void addFirst(Object obj){
        Node2 node = new Node2();
        node.setObj(obj);
        if(size == 0){
            fistNode = node;
            lastNode = node;
            size++;
            return;
        }
        fistNode.setPre(node);
        node.setNext(fistNode);
        fistNode = node;
        size++;
    }

    // 删除首元素
    public void removeFirst(){
        Node2 second = fistNode.getNext();
        fistNode.setNext(null);
        fistNode = second;
        size--;
    }

    public Object get(int index){
        if(index<0||index>=size){
            throw new IndexOutOfBoundsException("index="+index);
        }
        Node2 node = fistNode;
        for (int i = 0; i < index; i++) {
            node = node.getNext();
        }

        return node.getObj();
    }

    // 将obj插入到index
    public void add(int index,Object obj){
        if(index<0||index>=size){
            throw new IndexOutOfBoundsException("index="+index);
        }
        // 新node
        Node2 newnode = new Node2();
        // index上一个node
        Node2 prenode = fistNode;
        for (int i = 0; i < index-1; i++) {
            prenode = prenode.getNext();
        }
        // index-1处node
        Node2 node = prenode.getNext();
        prenode.setNext(newnode);
        newnode.setObj(obj);
        newnode.setNext(node);
        size++;
    }

    // 删除index
    public void remove(int index){
        if(index<0||index>=size){
            throw new IndexOutOfBoundsException("index="+index);
        }
        // 新node
        Node2 newnode = new Node2();
        // index上一个node
        Node2 prenode = fistNode;
        for (int i = 0; i < index-1; i++) {
            prenode = prenode.getNext();
        }
        prenode.setNext(prenode.getNext().getNext());
        size--;
    }
}

class Node2{
    private Object obj;
    private Node2 next;  // 下一个
    private Node2 pre;  // 上一个

    public Object getObj() {
        return obj;
    }

    public void setObj(Object obj) {
        this.obj = obj;
    }

    public Node2 getNext() {
        return next;
    }

    public void setNext(Node2 next) {
        this.next = next;
    }

    public Node2 getPre() {
        return pre;
    }

    public void setPre(Node2 pre) {
        this.pre = pre;
    }

    @Override
    public String toString() {
        return "Node2{" +
                "obj=" + obj +
                ", next=" + next +
                ", pre=" + pre +
                '}';
    }
}